//
//  SEGFeedbackDetailViewController.m
//  ExcellentHome
//
//  Created by liangxinqiang on 15-4-23.
//  Copyright (c) 2015年 陈区. All rights reserved.
//

#import "SEGFeedbackDetailViewController.h"
#import "SEGFeedbackDetailViewModel.h"

@interface SEGFeedbackDetailViewController ()
@property(nonatomic, strong) SEGFeedbackDetailViewModel *viewModel;
@end

@implementation SEGFeedbackDetailViewController
@synthesize sugId;

-(void)loadView
{
    [super loadView];

    m_tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0,  LYScreenWidth(), CGRectGetHeight(self.view.bounds) - kNavigationBarAndStatusBarHeight - 45 -LYSafeAreaBottom()) style:UITableViewStylePlain];
    m_tableView.delegate = self;
    m_tableView.dataSource = self;
    m_tableView.separatorStyle=UITableViewCellSelectionStyleNone;
    m_tableView.backgroundColor = kColor_W;
    [self.view addSubview:m_tableView];
    
    footView=[[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetHeight(self.view.bounds) - kNavigationBarAndStatusBarHeight -(45+LYSafeAreaBottom()), LYScreenWidth(), 45+LYSafeAreaBottom())];
    footView.backgroundColor=SEGAppearanceColor(kColor_bg, kColor_TABLE);
    [self.view addSubview:footView];
    
    inputTextView = [[UITextField alloc] initWithFrame:CGRectMake(15, 7.5, LYScreenWidth()-70, 30)];
    inputTextView.delegate = self;
    [inputTextView setUserInteractionEnabled:YES];
    inputTextView.font = [UIFont systemFontOfSize:15];
    inputTextView.textColor = kColor_2;
    inputTextView.returnKeyType = UIReturnKeySend;
    inputTextView.backgroundColor = kColor_W;
    inputTextView.layer.borderWidth = 0.5f;
    inputTextView.layer.borderColor = kColor_L2.CGColor;
    inputTextView.layer.cornerRadius = 5;
    inputTextView.placeholder = @"  填写您的回复"; 
    [footView addSubview:inputTextView];
    
    btnSendMsg = [UIButton buttonWithType:UIButtonTypeCustom];
    [btnSendMsg setTitle:@"发送" forState:UIControlStateNormal];
    [btnSendMsg.titleLabel setFont:[UIFont systemFontOfSize:14]];
    [btnSendMsg setTitleColor:kColor_T forState:UIControlStateNormal];
    [btnSendMsg addTarget:self action:@selector(btnSendMsgClicked:) forControlEvents:UIControlEventTouchUpInside];
    btnSendMsg.frame = CGRectMake(inputTextView.right +8, inputTextView.frame.origin.y, 46, 31);
    [footView addSubview:btnSendMsg];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=@"详情";
    [self showCustomNavigationBackButton];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(onKeyboardWillHideNotification:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(onKeyboardWillShowNotification:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    
    // Do any additional setup after loading the view.
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    //    [[BusinessManager sharedManager].systemAccountManager requestFeedbacDetail:self.sugId];
    [self requestFeedbacDetailWithId:self.sugId];
}

#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if ([string isEqualToString:@"\n"]) {
        [self requestReplyWithId:self.sugId WithContext:textField.text];
        [textField resignFirstResponder];
        textField.text=@"";
        return NO;
    }
    return YES;
}
#pragma mark - TextView Delegate


- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    
    if ([text isEqualToString:@"\n"]) {
        //        [[BusinessManager sharedManager].systemAccountManager requestReply:self.sugId context:textView.text];
        [self requestReplyWithId:self.sugId WithContext:textView.text];
        [textView resignFirstResponder];
        textView.text=@"";
        return NO;
    }
    return YES;
}

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
    return YES;
}


//发送按钮点击
- (void)btnSendMsgClicked:(UIButton *)sender
{
    //    [[BusinessManager sharedManager].systemAccountManager requestReply:self.sugId context:inputTextView.text];
    [self requestReplyWithId:self.sugId WithContext:inputTextView.text];
    [inputTextView resignFirstResponder];
    inputTextView.text=@"";
}
#pragma mark - notitication
- (void)onKeyboardWillHideNotification:(NSNotification *)aNotification
{
    UIScreen *scr = [UIScreen mainScreen];
    
    CGRect appbounds = CGRectMake(0, 0, scr.bounds.size.width, scr.bounds.size.height-kNavigationBarAndStatusBarHeight);
    [UIView animateWithDuration:0.3 animations:^{
        footView.frame=CGRectMake(0, appbounds.size.height-45-LYSafeAreaBottom(), appbounds.size.width, 45);
    }];
}

- (void)onKeyboardWillShowNotification:(NSNotification *)aNotification
{
    
    CGSize kbSize = [[[aNotification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    
    UIScreen *scr = [UIScreen mainScreen];
    
    CGRect appbounds = CGRectMake(0, 0, scr.bounds.size.width, scr.bounds.size.height-kNavigationBarAndStatusBarHeight);
    [UIView animateWithDuration:0.3 animations:^{
        footView.frame=CGRectMake(0, appbounds.size.height-45-kbSize.height, appbounds.size.width, 45);
    }];
    
    
}

#pragma mark - tableview delegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [[self.viewModel.listData objectForKey:@"ObjectArray"] count]+1;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row==0) {
        CGSize titleSize = [[self.viewModel.listData objectForKey:@"context"] sizeWithFont:[UIFont systemFontOfSize:16] constrainedToSize:CGSizeMake(LYScreenWidth()-30,2000) lineBreakMode:NSLineBreakByWordWrapping];
        
        return titleSize.height+65;
        
    }else{
        NSArray*objectArray=[self.viewModel.listData objectForKey:@"ObjectArray"];
        NSString*contextStr=[NSString stringWithFormat:@"%@:%@",[[objectArray objectAtIndex:indexPath.row-1] objectForKey:@"userName"],[[objectArray objectAtIndex:indexPath.row-1] objectForKey:@"context"]];
        CGSize labelsize = [contextStr sizeWithFont:[UIFont systemFontOfSize:13] constrainedToSize:CGSizeMake(LYScreenWidth()-35,2000) lineBreakMode:NSLineBreakByCharWrapping];
        return labelsize.height+15;
        
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSString *cellIdStr = [NSString stringWithFormat:@"cell%ld",(long)indexPath.row];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdStr];
    if(!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdStr];
        cell.backgroundColor = [UIColor clearColor];
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        if (indexPath.row==0) {
            
            UIView *line = [[UIView alloc] initWithFrame:CGRectMake(10, 64.5, cell.bounds.size.width, 0.5)];
            line.backgroundColor = kColor_L2;
            line.tag=1004;
            [cell.contentView addSubview:line];
            
            UILabel*title=[[UILabel alloc] initWithFrame:CGRectMake(15, 15, LYScreenWidth()-30, 16)];
            title.tag=1001;
            title.textColor=kColor_2;
            title.font=[UIFont systemFontOfSize:16];
            [title setNumberOfLines:0];
            title.lineBreakMode = NSLineBreakByCharWrapping;
            [cell.contentView addSubview:title];
            
            
            UILabel*time=[[UILabel alloc] initWithFrame:CGRectMake(15, 40, LYScreenWidth()-30, 10)];
            time.textColor=kColor_3;
            time.tag=1002;
            time.font=[UIFont systemFontOfSize:10];
            [cell.contentView addSubview:time];
            
            
        }else{
            
            UILabel*context=[[UILabel alloc] initWithFrame:CGRectMake(15, 0, LYScreenWidth()-35, 13)];
            context.tag=1003;
            context.textColor=kColor_2;
            context.font=[UIFont systemFontOfSize:13];
            [context setNumberOfLines:0];
            context.lineBreakMode = NSLineBreakByCharWrapping;
            [cell.contentView addSubview:context];
            
            
        }
        
        
    }
    
    UILabel*title=(UILabel*)[cell.contentView viewWithTag:1001];
    UILabel*time=(UILabel*)[cell.contentView viewWithTag:1002];
    UILabel*context=(UILabel*)[cell.contentView viewWithTag:1003];
    UIView*line=(UIView*)[cell.contentView viewWithTag:1004];
    
    
    title.text=[self.viewModel.listData objectForKey:@"context"];
    time.text=[self.viewModel.listData  objectForKey:@"createDate"];
    CGSize titleSize = [title.text sizeWithFont:[UIFont systemFontOfSize:16] constrainedToSize:CGSizeMake(LYScreenWidth()-30,2000) lineBreakMode:NSLineBreakByWordWrapping];
    title.frame=CGRectMake(15, 15, LYScreenWidth()-30, titleSize.height);
    time.frame=CGRectMake(15, 25+titleSize.height, LYScreenWidth()-30, 10);
    line.frame=CGRectMake(10, titleSize.height+49.5, cell.bounds.size.width, 0.5);
    
    NSArray*objectArray=[self.viewModel.listData objectForKey:@"ObjectArray"];
    
    if (indexPath.row>0) {
        NSDictionary *dict = [objectArray objectAtIndex:indexPath.row-1];
        // 优化以前的反馈显示旧昵称问题 （消息若用户为当前用户，显示当前的用户昵称）
        NSString *userName;
        if ([[[dict objectForKey:@"userId"] stringValue] isEqualToString:kAccountUserID]) {
            userName = kAccountNickName;
        }else {
            userName = [dict objectForKey:@"userName"];
        }
        NSString*contextStr=[NSString stringWithFormat:@"%@:%@",userName,[dict objectForKey:@"context"]];
        
        NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:contextStr];
        if ([[dict objectForKey:@"userType"] intValue]==2) {
            [str addAttribute:NSForegroundColorAttributeName value:kColor_T range:NSMakeRange(0,[[dict objectForKey:@"userName"] length])];
            
        }else if (([[dict objectForKey:@"userType"] intValue]==1)){//自己发的反馈消息
            [str addAttribute:NSForegroundColorAttributeName value:kColor_3 range:NSMakeRange(0,[userName length])];
        }
        
        context.attributedText=str;
        
        CGSize labelsize = [contextStr sizeWithFont:[UIFont systemFontOfSize:13] constrainedToSize:CGSizeMake(LYScreenWidth()-35,2000) lineBreakMode:NSLineBreakByWordWrapping];
        [context setFrame:CGRectMake(15, 0, labelsize.width, labelsize.height)];
    }
    return cell;
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [inputTextView resignFirstResponder];
    
}

#pragma mark - UITraitEnvironment
- (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection {
    [super traitCollectionDidChange:previousTraitCollection];
    inputTextView.layer.borderColor = kColor_L2.CGColor;
}

#pragma mark - 新网络请求
- (void)requestFeedbacDetailWithId:(NSString *)sugIdStr
{
    [self.viewModel requestFeedbackDetailWithSugId:sugIdStr completed:^(NSString * _Nonnull code) {
        if ([code isEqualToString:@"0"]){
            [self->m_tableView reloadData];
        }
    }];
}

- (void)requestReplyWithId:(NSString *)sugIdStr WithContext:(NSString *)contextStr
{
    [self.viewModel requestSendReplyWithContextWithId:sugIdStr WithContext:contextStr completed:^(NSString * _Nonnull code, NSString * _Nonnull message) {
        if (![code isEqualToString:@"0"]) {
            
            UIAlertView* alertview = [[UIAlertView alloc] initWithTitle:nil
                                                                message:message
                                                               delegate:nil
                                                      cancelButtonTitle:@"确认"
                                                      otherButtonTitles:nil];
            [alertview show];
            return;
        }
        [self requestFeedbacDetailWithId:sugIdStr];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - init Views
-(void)segInitViews{

}

#pragma mark - RAC Data Binding
- (void)bindViewModel {
}

#pragma mark - getter
-(SEGFeedbackDetailViewModel *)viewModel{
    if (!_viewModel) {
        _viewModel = [[SEGFeedbackDetailViewModel alloc]init];
    }
    return _viewModel;
}
@end
